package com.neu.questionnaireplus.controller;

import cn.hutool.crypto.digest.MD5;
import com.neu.questionnaireplus.entity.HttpResponseEntity;
import com.neu.questionnaireplus.entity.Tenement;
import com.neu.questionnaireplus.entity.User;
import com.neu.questionnaireplus.service.MsmService;
import com.neu.questionnaireplus.service.TenementService;
import com.neu.questionnaireplus.service.UserService;
import com.neu.questionnaireplus.utils.common.CommonUtils;
import com.neu.questionnaireplus.utils.constant.HttpStatus;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Description: 使用swagger进行测试, url未使用rap2的，项目整合时再做修改
 * @Param:
 * @return:
 * @Author: ~FHX~ (:TSunS:)
 * @Date: 2022/10/30
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
@Api("用户服务")
@Validated
public class UserController {

  @Autowired
  private UserService userService;

  @Autowired
  private MsmService msmService;

  @Autowired
  private TenementService tenementService;

  /**
   * @Description: map用来暂时存储短信验证码，key是手机号，value是验证码 ,ConcurrentHashMap保障并发安全
   * @Param:
   * @return:
   * @Author: ~FHX~ (:TSunS:)
   * @Date: 2022/11/2
   */
  private Map<String, String> loginmap = new ConcurrentHashMap<String, String>();
  private Map<String, String> registermap = new ConcurrentHashMap<String, String>();
  private Map<String, String> resetPwdmap = new ConcurrentHashMap<String, String>();

  @ApiOperation("显示密保问题(传递回整个用户)")
  @RequestMapping(value = "/showUserSec", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity showUserSec(@RequestBody Map<String, Object> map) {
    HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
    try {
      String username = map.get("username").toString();
      User user = userService.queryUserByUsername(username);
      if (user != null && user.getStatus() != 1 && user.getDelFlag() != 1){
        httpResponseEntity
            .setCode(HttpStatus.SUCCESS)
            .setData(user)
            .setMessage("success");
      }else {
        httpResponseEntity
            .setCode(HttpStatus.ERROR)
            .setData(null)
            .setMessage("租户不存在或无法登录");
      }
    } catch (Exception e) {
      httpResponseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return httpResponseEntity;
    }
  }

  @ApiOperation("注册用户时发送短信")
  @RequestMapping(value = "/registersmsUser", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity registerSms(@RequestBody Map<String, Object> map) {
    HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
    try {
      String phone = map.get("phone").toString();
      String s = msmService.registerSend("86" + phone);
      registermap.put(phone, s);
      httpResponseEntity
          .setCode(HttpStatus.SUCCESS)
          .setData(s)
          .setMessage("success");
    } catch (Exception e) {
      httpResponseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return httpResponseEntity;
    }
  }

  @ApiOperation("用户登录时发送短信")
  @RequestMapping(value = "/loginSmsUser", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity loginSms(@RequestBody Map<String, Object> map) {
    HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
    try {
      String phone = map.get("phone").toString();
      String s = msmService.loginSend("86" + phone);
      loginmap.put(phone, s);
      httpResponseEntity
          .setCode(HttpStatus.SUCCESS)
          .setData(s)
          .setMessage("success");
    } catch (Exception e) {
      httpResponseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return httpResponseEntity;
    }
  }

  @ApiOperation("用户找回密码时发送短信")
  @RequestMapping(value = "/findPwdSmsUser", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity findPwdSms(@RequestBody Map<String, Object> map) {
    HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
    try {
      String phone = map.get("phone").toString();
      String s = msmService.resetPwdSend("86" + phone);
      resetPwdmap.put(phone, s);
      httpResponseEntity
          .setCode(HttpStatus.SUCCESS)
          .setData(s)
          .setMessage("success");
    } catch (Exception e) {
      httpResponseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return httpResponseEntity;
    }
  }

  /**
   * @Description: 注意一个方法中的参数只能有一个RequestBody
   * @Param: [user, str]
   * @return: com.neu.questionnaireplus.entity.HttpResponseEntity
   * @Author: ~FHX~ (:TSunS:)
   * @Date: 2022/11/2
   */
  @ApiOperation("发送短信后注册")
  @RequestMapping(value = "/registerUser", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity registerUser(@RequestBody Map<String, Object> map) {
    HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
    try {
      String telnumber = map.get("telnumber").toString();
      boolean b = userService.checkRegisterStr(telnumber, map.get("str").toString(),
          registermap.get(telnumber));
      if (b) {
        User user1 = new User();
        user1
            .setDelFlag(0)
            .setStatus(0)
            .setCreatedDate(CommonUtils.getDateByDateString(CommonUtils.getFormatDateTimeNow()))
            .setId(CommonUtils.getUUID())
            .setPassword(MD5.create().digestHex(map.get("password").toString()))
            .setUsername(map.get("username").toString())
            .setSecurityQuestionAnswer(map.get("securityQuestionAnswer").toString())
            .setSecurityQuestionContext(map.get("securityQuestionContext").toString())
            .setBelongTenement(map.get("TenementName").toString())
            .setTelnumber(telnumber)
            .setCurpaper(0)
            .setMaxpaper(0);

        userService.insertUser(user1);
        httpResponseEntity
            .setCode(HttpStatus.SUCCESS)
            .setData(user1)
            .setMessage("success");
      } else {
        httpResponseEntity
            .setCode(HttpStatus.ERROR)
            .setData(null)
            .setMessage("验证码错误");
      }
    } catch (Exception e) {
      httpResponseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return httpResponseEntity;
    }
  }

  @ApiOperation("通过密码登录")
  @RequestMapping(value = "/loginByPwdUser", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity loginByPwd(@RequestBody Map<String, Object> map) {
    HttpResponseEntity responseEntity = new HttpResponseEntity();
    try {
      String username = map.get("username").toString();
      String password = map.get("password").toString();
      boolean b = userService.loginByPassword(username, MD5.create().digestHex(password));
      User user = userService.queryUserByUsername(username);
      if (b) {
        responseEntity
            .setCode(HttpStatus.SUCCESS)
            .setData(user)
            .setMessage("success");
      } else {
        responseEntity
            .setCode(HttpStatus.ERROR)
            .setData(null)
            .setMessage("用户名或密码错误");
      }
    } catch (Exception e) {
      responseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return responseEntity;
    }
  }

  @ApiOperation("通过短信验证码登录")
  @RequestMapping(value = "/loginBySmsUser", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity loginBySms(@RequestBody Map<String, Object> map) {
    HttpResponseEntity responseEntity = new HttpResponseEntity();
    try {
      String phone = map.get("phone").toString();
      String str = map.get("str").toString();
      boolean b = userService.loginByPhone(phone, str, loginmap.get(phone));
      User user = userService.queryUserByPhone(phone);
      if (b) {
        responseEntity
            .setCode(HttpStatus.SUCCESS)
            .setData(user)
            .setMessage("success");
      } else {
        responseEntity
            .setCode(HttpStatus.ERROR)
            .setData(null)
            .setMessage("手机号或短信验证码错误");
      }
    } catch (Exception e) {
      responseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return responseEntity;
    }
  }

  @ApiOperation("通过密保找回密码（验证密保）")
  @RequestMapping(value = "/checkSecUser", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity checkSec(@RequestBody Map<String, Object> map) {
    HttpResponseEntity responseEntity = new HttpResponseEntity();
    try {
      String securityQuestionAnswer = map.get("securityQuestionAnswer").toString();
      String username = map.get("username").toString();
      boolean b = userService.checkSecurityQuestion(username, securityQuestionAnswer);
      if (b) {
        responseEntity
            .setCode(HttpStatus.SUCCESS)
            .setData(b)
            .setMessage("success");
      } else {
        responseEntity
            .setCode(HttpStatus.ERROR)
            .setData(null)
            .setMessage("密保或用户名错误");
      }
    } catch (Exception e) {
      responseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return responseEntity;
    }
  }


  @ApiOperation("找回密码（重置密码）")
  @RequestMapping(value = "/resetPwdUser", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity resetPwd(@RequestBody Map<String, Object> map) {
    HttpResponseEntity responseEntity = new HttpResponseEntity();
    try {
      String username = map.get("username").toString();
      User user = userService.queryUserByUsername(username);
      if (user != null) {
        String newpassword = map.get("newpassword").toString();
        user.setPassword(MD5.create().digestHex(newpassword));
        boolean b = userService.updateUser(user);
        if (b) {
          responseEntity
              .setCode(HttpStatus.SUCCESS)
              .setData(user)
              .setMessage("success");
        } else {
          responseEntity
              .setCode(HttpStatus.ERROR)
              .setData(null)
              .setMessage("修改失败");
        }
      } else {
        responseEntity
            .setCode(HttpStatus.ERROR)
            .setData(null)
            .setMessage("用户不存在");
      }
    } catch (Exception e) {
      responseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return responseEntity;
    }
  }


  @ApiOperation("创建用户")
  @RequestMapping(value = "/createUser", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity createUser(@RequestBody Map<String, Object> map) {
    HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
    try {
      User user = new User();
      user
          .setDelFlag(0)
          .setStatus(0)
          .setCreatedDate(CommonUtils.getDateByDateString(CommonUtils.getFormatDateTimeNow()))
          .setId(CommonUtils.getUUID())
          .setPassword(MD5.create().digestHex(map.get("password").toString()))
          .setUsername(map.get("username").toString())
          .setSecurityQuestionAnswer(map.get("securityQuestionAnswer").toString())
          .setSecurityQuestionContext(map.get("securityQuestionContext").toString())
          .setTelnumber(map.get("telnumber").toString())
          .setCurpaper(0)
          .setMaxpaper(Integer.parseInt(map.get("maxpaper").toString()))
          .setBelongTenement(map.get("tenement").toString());

      userService.insertUser(user);
      httpResponseEntity
          .setCode(HttpStatus.SUCCESS)
          .setData(user)
          .setMessage("success");
    } catch (Exception e) {
      httpResponseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return httpResponseEntity;
    }
  }

  @ApiOperation("改变用户状态")
  @RequestMapping(value = "/changeUserStatus", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity changeUserStatus(@RequestBody Map<String, Object> map) {
    HttpResponseEntity responseEntity = new HttpResponseEntity();
    try {
      String username = map.get("username").toString();
      User user = userService.queryUserByUsername(username);
      if (user != null) {
        boolean b = user.getStatus() == 1 ? userService.freeUser(user.getId()) : userService.forbiddenUser(user.getId()) ;
        if (b) {
          responseEntity
              .setCode(HttpStatus.SUCCESS)
              .setData(user)
              .setMessage("success");
        } else {
          responseEntity
              .setCode(HttpStatus.ERROR)
              .setData(null)
              .setMessage("用户状态改变失败");
        }
      } else {
        responseEntity
            .setCode(HttpStatus.ERROR)
            .setData(null)
            .setMessage("用户不存在");
      }
    } catch (Exception e) {
      responseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return responseEntity;
    }
  }

  @ApiOperation("修改用户信息")
  @RequestMapping(value = "/updateUser", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity updateUser(@RequestBody Map<String, Object> map) {
    HttpResponseEntity responseEntity = new HttpResponseEntity();
    try {
      String id = map.get("id").toString();
      User user = userService.queryUserByID(id);
      if (user != null) {
        String username = map.get("username").toString();
        String telnumber = map.get("telnumber").toString();
        String securityQuestionAnswer = map.get("securityQuestionAnswer").toString();
        String securityQuestionContext = map.get("securityQuestionContext").toString();
        user
            .setUsername(username)
            .setTelnumber(telnumber)
            .setSecurityQuestionAnswer(securityQuestionAnswer)
            .setSecurityQuestionContext(securityQuestionContext)
            .setStatus(Integer.valueOf(map.get("status").toString()))
            .setMaxpaper(Integer.valueOf(map.get("maxpaper").toString()));
        boolean b = userService.updateUser(user);
        if (b) {
          responseEntity
              .setCode(HttpStatus.SUCCESS)
              .setData(telnumber)
              .setMessage("success");
        } else {
          responseEntity
              .setCode(HttpStatus.ERROR)
              .setData(null)
              .setMessage("修改失败");
        }
      } else {
        responseEntity
            .setCode(HttpStatus.ERROR)
            .setData(null)
            .setMessage("用户不存在");
      }
    } catch (Exception e) {
      responseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return responseEntity;
    }
  }

  @ApiOperation("删除用户（伪删除）")
  @RequestMapping(value = "/deleteUser", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity deleteUser(@RequestBody Map<String, Object> map) {
    HttpResponseEntity responseEntity = new HttpResponseEntity();
    try {
      String username = map.get("username").toString();
      User user = userService.queryUserByUsername(username);
      if (user != null) {
        boolean b = userService.deleteUserInfo(user);
        if (b) {
          responseEntity
              .setCode(HttpStatus.SUCCESS)
              .setData(user)
              .setMessage("success");
        } else {
          responseEntity
              .setCode(HttpStatus.ERROR)
              .setData(null)
              .setMessage("用户删除失败");
        }
      } else {
        responseEntity
            .setCode(HttpStatus.ERROR)
            .setData(null)
            .setMessage("用户不存在");
      }
    } catch (Exception e) {
      responseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return responseEntity;
    }
  }


  @ApiOperation("展示所有未被删除的用户")
  @RequestMapping(value = "/showUser", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity showAllUsers(@RequestBody Map<String,Object> map) {
    HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
    try {
      String belongTenement = map.get("belongTenement").toString();
      List<User> users = userService.queryUserByTenement(belongTenement);
      httpResponseEntity
          .setCode(HttpStatus.SUCCESS)
          .setData(users)
          .setMessage("success");
    } catch (Exception e) {
      httpResponseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return httpResponseEntity;
    }
  }

  @ApiOperation("模糊查询所有未被删除的用户")
  @RequestMapping(value = "/showQueryUser", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity showQueryUsers(@RequestBody Map<String, Object> map) {
    HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
    try {
      String queryStr = map.get("queryStr").toString();
      List<User> users = userService.queryUserByName(queryStr);
      httpResponseEntity
          .setCode(HttpStatus.SUCCESS)
          .setData(users)
          .setMessage("success");
    } catch (Exception e) {
      httpResponseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return httpResponseEntity;
    }
  }

  @ApiOperation("批量导入用户")
  @RequestMapping(value = "/importFileToUsers", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity importFileToUsers(@RequestParam(value = "file")MultipartFile file,@RequestParam(value = "tenement") String tenementname) {
    HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
    try {
      Tenement tenement = tenementService.queryTenementByUsername(tenementname);
      if (tenement != null){
        List<User> list = userService.importFileToUsers(tenement, file);
        httpResponseEntity
            .setCode(HttpStatus.SUCCESS)
            .setData(list)
            .setMessage("success");
      }else {
        httpResponseEntity
            .setCode(HttpStatus.ERROR)
            .setData(null)
            .setMessage("租户名可能已被删除");
      }
    } catch (Exception e) {
      httpResponseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return httpResponseEntity;
    }
  }

}
